package com.zdy.socketserver.sound;

import com.baidu.aip.speech.AipSpeech;
import com.baidu.aip.speech.TtsResponse;
import com.baidu.aip.util.Util;
import com.jacob.activeX.ActiveXComponent;
import com.jacob.com.Dispatch;
import com.jacob.com.Variant;
import org.jaudiotagger.audio.AudioFile;
import org.jaudiotagger.audio.AudioFileIO;
import org.jaudiotagger.audio.exceptions.CannotReadException;
import org.jaudiotagger.audio.exceptions.InvalidAudioFrameException;
import org.jaudiotagger.audio.exceptions.ReadOnlyFileException;
import org.jaudiotagger.tag.TagException;
import org.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import sun.audio.AudioPlayer;
import sun.audio.AudioStream;

import javax.annotation.PostConstruct;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.Queue;

/**
 * @author myh
 * @date 2024/6/13
 */
@Component
public class Sound1 extends Thread {

    private static final Logger log = LoggerFactory.getLogger(Sound1.class);

    //tts语音播报队列
    private static Queue<String> strList = new LinkedList<>();

    private static Thread tts = new Thread();
    //播放音乐
    private static AudioStream as = null;
    public static final String APP_ID = "94867527";
    public static final String API_KEY = "ndjt4zd7YsjkfbkIxfAd6vcz";
    public static final String SECRET_KEY = "siDcenPkBe7EyoLAFbVOScYrovAiUMiP";

    private static final String FOLDER_PATH = "D:\\sound";

    //语速，取值0-9，默认为5中语速
    private static final String SPD = "3";

    //普通发音人选择：度小美=0(默认)，度丫丫=4
    //精品音库：度小鹿=5118
    private static final String PER = "5118";

    /*将播报语音添加到队列中*/
    public void call(String text) {
        //文件名称
        long t1 = System.currentTimeMillis();
        String fileName = String.valueOf(t1);
        strList.add(fileName);
        try {
            // 初始化一个AipSpeech
            AipSpeech client = new AipSpeech(APP_ID, API_KEY, SECRET_KEY);

            // 可选：设置网络连接参数
            client.setConnectionTimeoutInMillis(20000);
            client.setSocketTimeoutInMillis(60000);

            // 可选：设置代理服务器地址, http和socket二选一，或者均不设置
//        client.setHttpProxy("proxy_host", proxy_port);  // 设置http代理
//        client.setSocketProxy("proxy_host", proxy_port);  // 设置socket代理

            // 调用接口
            HashMap<String, Object> options = new HashMap<>();
            options.put("spd", SPD);//语速
            options.put("per", PER);//发音人
            options.put("aue", 6);//wav格式

            TtsResponse res = client.synthesis(text, "zh", 1, options);
            byte[] data = res.getData();
            JSONObject res1 = res.getResult();
            if (data != null) {
                //文件名称
                File folder = new File(FOLDER_PATH);
                if (!folder.exists()) {
                    boolean mkdir = folder.mkdir();
                    if (!mkdir) {
                        log.error("创建文件夹失败");
                    }
                }
                Util.writeBytesToFileSystem(data, "D:\\sound\\" + fileName + ".wav");
            }
            if (res1 != null) {
                log.info("res1" + res1.toString(2));
            }
            //播放音频
            ttsPlayer();
        } catch (Exception e) {
            e.printStackTrace();
            log.info(e.getMessage());
        }
    }

    /**
     * 播放音频
     */
    @PostConstruct
    public void ttsPlayerInit() {
        //判断线程状态
        if (!tts.isAlive()) {
            tts = new Thread() {
                public void run() {
                    //是否正在播放音乐
//                    if (t.isAlive()) {
//                        ttsStop();
//                    }
                    //播放音频
                    ttsPlayer();
                }
            };
            tts.start();
        }


    }

    public void ttsPlayer() {

        while (!strList.isEmpty()) {
            //输出音频时长
            String fileName = strList.poll();
            File file = new File("D:\\sound\\" + fileName + ".wav");

            try (FileInputStream fileInputStream = new FileInputStream(file);
                 AudioStream as = new AudioStream(fileInputStream)) {
                AudioFile mp3 = AudioFileIO.read(file);
                // 开始播放
                log.info("开始播放声音");
                AudioPlayer.player.start(as);
                // 精确等待音频播放完成，但需注意sleep的不精确性
                Thread.sleep(mp3.getAudioHeader().getTrackLength() * 1000L + 500);
                log.info("声音播放完成");
            } catch (InterruptedException | CannotReadException | IOException | TagException |
                     ReadOnlyFileException |
                     InvalidAudioFrameException e) {
                e.printStackTrace();
                log.error("播放音频失败" + e.getMessage());
                Thread.currentThread().interrupt(); // 重新设置中断状态

                throw new RuntimeException(e);
            }

            //删除播放完成的音频
            boolean delete = file.delete();
            log.info(fileName + "删除文件：" + delete);
        }

    }


    /*文字转语音播报停止*/
    public void ttsStop() {
        try {
            //停止线程
            tts.interrupt();
            //停止播报
            AudioPlayer.player.stop(as);
            //清空列表所有元素
            strList.clear();

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}
